//
//  Utility.m
//  ZTML
//
//  Created by hdz on 17/11/6.
//  Copyright (c) 2017年 long. All rights reserved.
//

#import "Utility.h"
#import <Accelerate/Accelerate.h>
#import <AVFoundation/AVFoundation.h>

@implementation Utility

/**
 获取当前视图
 
 @return return value description
 */
+ (UIViewController *)currentViewController
{
    UIViewController *result = nil;
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return [self getTopViewController:result];
}

+ (UIViewController *)getTopViewController:(UIViewController *)viewController {
    if ([viewController isKindOfClass:[UITabBarController class]]) {
        return [self getTopViewController:[(UITabBarController *)viewController selectedViewController]];
    } else if ([viewController isKindOfClass:[UINavigationController class]]) {
        return [self getTopViewController:[(UINavigationController *)viewController topViewController]];
    } else if (viewController.presentedViewController) {
        return [self getTopViewController:viewController.presentedViewController];
    } else {
        return viewController;
    }
}

/**
 弹出消息提示框
 
 @param atMessage 消息
 */
+ (void)showAlertMessage:(NSString *)atMessage
{
    [self showAlertTitle:nil Message:atMessage];
}

/**
 *  弹出消息提示框
 *
 *  @param atTitle   标题
 *  @param atMessage 消息
 */
+ (void)showAlertTitle:(NSString *)atTitle Message:(NSString *)atMessage
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:atTitle message:atMessage preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel                                                                 handler:^(UIAlertAction * action) {
    }];
    [alertController addAction:confirmAction];
    [[self currentViewController] presentViewController:alertController animated:YES completion:nil];
}

/**
 *  同步判断网络连接
 *
 *  @return YES 表示有网络连接
 */
+ (BOOL)networkDetection
{
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
    return (response != nil);
}

/**
 *  获取主窗口
 *
 *  @return return value description
 */
+ (UIWindow *)mainWindow
{
    UIApplication *app = [UIApplication sharedApplication];
    if ([app.delegate respondsToSelector:@selector(window)])
    {
        return [app.delegate window];
    }
    else
    {
        return [app keyWindow];
    }
}


/**
 验证验证码
 
 @param mobileNum 验证码
 @return YES，正确，NO，错误
 */
+ (BOOL)isNumber:(NSString *)mobileNum
{
    NSString *MOBILE = @"[0-9]{6}";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:mobileNum];
}


/**
 验证手机号
 
 @param mobileNum 手机号
 @return YES，正确，NO，错误
 */
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString *MOBILE = @"[0-9]{11}";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:mobileNum];
}


/**
 验证字符串
 
 @param string 字符串
 @return YES，错误，NO，正确
 */
+ (BOOL)isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;
    }
    return NO;
}


/**
 按钮倒计时
 
 @param sender 按钮
 */
+ (void)startTime:(UIButton *)sender
{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                [sender setTitleColor:kColorMainTheme forState:UIControlStateNormal];
                [sender setUserInteractionEnabled:YES];
            });
        }else{
            int seconds = timeout%60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:[NSString stringWithFormat:@"%@秒后重新获取",strTime] forState:UIControlStateNormal];
                [sender setTitleColor:kColorText forState:UIControlStateNormal];
                [sender setUserInteractionEnabled:NO];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

}

+ (void)startTime:(UIButton *)sender withArrTitles:(NSArray *)titles
{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:titles.firstObject forState:UIControlStateNormal];
                [sender setTitleColor:kColorMainTheme forState:UIControlStateNormal];
                [sender setUserInteractionEnabled:YES];
            });
        }else{
            int seconds = timeout%60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [sender setTitle:[NSString stringWithFormat:@"%@%@",strTime,titles.lastObject] forState:UIControlStateNormal];
                [sender setTitleColor:kColorText forState:UIControlStateNormal];
                [sender setUserInteractionEnabled:NO];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

/**
 获取当前时间戳
 
 @param date 当前时间
 @return 时间戳
 */
+ (NSString *)currentTime:(NSDate *)date
{
    NSString *curTime = [NSString stringWithFormat:@"%d", (int)[date timeIntervalSince1970]];
    return curTime;
}

/**
 *  检测文字的Size
 *
 *  @param text             文字
 *  @param font             字体
 *  @param width            最大宽度
 *  @param attributedString 富文本（如果attributedString不为nil 会根据attributedString来检测）
 *
 *  @return 文字的Size
 */
+ (CGSize)getTextString:(NSString *)text textFont:(UIFont *)font frameWidth:(float)width attributedString:(NSMutableAttributedString *)attributedString
{
    CGSize constraint = CGSizeMake(width, MAXFLOAT);
    
    if (!attributedString) {
        
        attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
                                                                                               NSFontAttributeName:font
                                                                                               }];
        
    }
    CGRect rect = [attributedString boundingRectWithSize:constraint
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                                 context:nil];
    CGSize size = rect.size;
    return size;
}


/**
 时间戳转换时间
 
 @param timeInterval 时间戳
 @param format 时间格式
 @return 时间字符串
 */
+ (NSString *)exchageTimeInterval:(NSInteger)timeInterval format:(NSString *)format
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    return [self exchageDate:date format:format];
}

/**
 NSDate转NSString
 
 @param date 日期
 @param format 时间格式
 @return NSString
 */
+ (NSString *)exchageDate:(NSDate *)date format:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateStyle = NSDateFormatterMediumStyle;
    formatter.timeStyle = NSDateFormatterShortStyle;
    formatter.dateFormat = format;
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    return [formatter stringFromDate:date];
}

+ (NSTimeInterval)decodeNormalDate:(NSString *)normalDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateStyle = NSDateFormatterMediumStyle;
    formatter.timeStyle = NSDateFormatterShortStyle;
    formatter.dateFormat = [@"YYYY-MM-dd HH:mm:ss" substringToIndex:normalDate.length];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    formatter.timeZone = timeZone;
    NSDate *date = [formatter dateFromString:normalDate];
    return [date timeIntervalSince1970];
}

+ (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

/**
 判断字符串是否是Emoji
 
 @param string 字符串
 @return YES，是，NO，否
 */
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                    
                                } else if (substring.length > 1) {
                                    
                                    const unichar ls = [substring characterAtIndex:1];
                                    
                                    if (ls == 0x20e3) {
                                        
                                        returnValue = YES;
                                    }
                                    
                                } else {
                                    if (0x2792 <= hs && hs <= 0x278B) {
                                        
                                        returnValue = YES;
                                        
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        
                                        returnValue = YES;
                                        
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        
                                        returnValue = YES;
                                        
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        
                                        returnValue = YES;
                                        
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        
                                        returnValue = YES;
                                        
                                    }
                                    
                                }
                                
                            }];
    return returnValue;
}


/**
 *  截取当前屏幕
 *
 *  @return NSData *
 */
+ (NSData *)dataWithScreenshotInPNGFormat
{
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation))
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft)
        {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        }
        else if (orientation == UIInterfaceOrientationLandscapeRight)
        {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
        {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        }
        else
        {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImagePNGRepresentation(image);
}

/**
 *  返回截取到的图片
 *
 *  @return UIImage *
 */
+ (UIImage *)imageWithScreenshot
{
    NSData *imageData = [self dataWithScreenshotInPNGFormat];
    return [UIImage imageWithData:imageData];
}


/**
 创建线条
 
 @param rect 线条范围
 @param lineColor 线条颜色
 @return 线条
 */
+ (UIView *)initLineRect:(CGRect)rect lineColor:(UIColor *)lineColor
{
    UIView *line = [[UIView alloc] initWithFrame:rect];
    line.backgroundColor = lineColor;
    return line;
}

/**
 画圆
 
 @param rect rect description
 @param size size description
 @return return value description
 */
+ (CAShapeLayer *)setLayerWithRect:(CGRect)rect radii:(CGSize)size
{
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight | UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = rect;
    // 将曲线路径设置为layer的路径
    maskLayer.path = path.CGPath;
    
    return maskLayer;
}

/**
 富文本处理
 
 @param label   对象
 @param font    对象字体
 @param range   有效范围
 @param vaColor 颜色
 */
+ (void)fuwenbenLabel:(UILabel *)label fontNumber:(id)font andRange:(NSRange)range andColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    [str addAttribute:NSFontAttributeName value:font range:range];
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    label.attributedText = str;
}


/**
 显示日期
 
 @param msglastTime 需要显示的时间戳
 @param showDetail 是否显示详细日期
 @return 日期
 */
+ (NSString *)showTime:(NSTimeInterval)msglastTime showDetail:(BOOL)showDetail
{
    NSDate *nowDate = [NSDate date];
    NSDate *msgDate = [NSDate dateWithTimeIntervalSince1970:msglastTime];
    NSCalendarUnit components = (NSCalendarUnit)(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute);
    NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar] components:components fromDate:nowDate];
    NSDateComponents *msgDateComponents = [[NSCalendar currentCalendar] components:components fromDate:msgDate];
    
    NSString *result = nil;
    if (nowDateComponents.year == msgDateComponents.year) {
        CGFloat maxInterval = ([nowDate timeIntervalSince1970] - msglastTime) / (24 * 3600);
        if (maxInterval < 3 && nowDateComponents.day == msgDateComponents.day) {
            result = [[NSString alloc] initWithFormat:@"%02d:%02d", (int)msgDateComponents.hour, (int)msgDateComponents.minute];
        }
        else if (maxInterval < 3 && nowDateComponents.day == (msgDateComponents.day + 1)) {
            result = showDetail ? [[NSString alloc] initWithFormat:@"昨天 %02d:%02d", (int)msgDateComponents.hour, (int)msgDateComponents.minute] : @"昨天";
        }
        else if (maxInterval < 3 && nowDateComponents.day == (msgDateComponents.day + 2)) {
            result = showDetail ? [[NSString alloc] initWithFormat:@"前天 %02d:%02d", (int)msgDateComponents.hour, (int)msgDateComponents.minute] : @"前天";
        }
        else if (maxInterval < 7 && nowDateComponents.weekday != msgDateComponents.weekday) {
            NSString *weekDay = [self weekdayStr:msgDateComponents.weekday];
            result = showDetail ? [weekDay stringByAppendingFormat:@" %02d:%02d", (int)msgDateComponents.hour, (int)msgDateComponents.minute] : weekDay;
        }
        else
        {
            NSString *data = [NSString stringWithFormat:@"%zd月%zd日", msgDateComponents.month, msgDateComponents.day];
            result = showDetail ? [data stringByAppendingFormat:@" %02d:%02d", (int)msgDateComponents.hour, (int)msgDateComponents.minute] : data;
        }
    }
    else
    {
        NSString *data = [NSString stringWithFormat:@"%zd年%zd月%zd日", msgDateComponents.year, msgDateComponents.month, msgDateComponents.day];
        result = showDetail ? [data stringByAppendingFormat:@" %02d:%02d", (int)msgDateComponents.hour, (int)msgDateComponents.minute] : data;
    }
    return result;
}

+ (NSString *)weekdayStr:(NSInteger)dayOfWeek
{
    static NSDictionary *daysOfWeekDict = nil;
    daysOfWeekDict = @{@(1):@"星期日",
                       @(2):@"星期一",
                       @(3):@"星期二",
                       @(4):@"星期三",
                       @(5):@"星期四",
                       @(6):@"星期五",
                       @(7):@"星期六",};
    return [daysOfWeekDict objectForKey:@(dayOfWeek)];
}


/**
 验证身份证号码
 
 @param identityString 身份证号码
 @return YES，是，NO，否
 */
+ (BOOL)judgeIdentityStringValid:(NSString *)identityString {
    
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if (![identityStringPredicate evaluateWithObject:identityString]) return NO;
    
    //** 开始进行校验 *//
    
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0; i < 17; i++) {
        NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum += subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod = idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast = [identityString substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod == 2) {
        if(![idCardLast isEqualToString:@"X"] || [idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }
    else {
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}

/**
 邮箱验证
 
 @param email 邮箱
 @return return value description
 */
+ (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/**
 获取导航栏view
 
 @return return value description
 */
//+ (UIView *)currentNavigationView
//{
//    return [[(AppDelegate *)[[UIApplication sharedApplication] delegate] rootViewController] view];
//}

/**
 下载单张图片
 
 @param urlString 图片网络地址
 @param success 图片
 */
//+ (void)downloadImageWithURLString:(NSString *)urlString success:(void (^)(UIImage *))success
//{
//    [SDWebImageManager.sharedManager loadImageWithURL:[NSURL URLWithString:urlString] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
//        if (image && success) {
//            success(image);
//        }
//    }];
//}

/**
 下载图片组
 
 @param urlStrings 图片网络地址
 @param success 图片
 */
+ (void)downloadImageWithURLStrings:(NSArray *)urlStrings success:(void (^)(NSMutableArray<UIImage *> *images))success
{
    __block NSInteger index = 0;
    NSMutableArray *images = [NSMutableArray array];
    for (NSString *urlString in urlStrings) {
        [self downloadImageWithURLString:urlString success:^(UIImage *image) {
            index ++;
            [images addObject:image];
            if (urlStrings.count == index) {
                success(images);
            }
        }];
    }
}


/**
 vImage高斯模糊
 
 @param image 原图
 @param blur 模糊度数
 @return 模糊图
 */
+ (UIImage *)boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur {
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 40);
    boxSize = boxSize - (boxSize % 2) + 1;
    
    CGImageRef img = image.CGImage;
    
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    
    void *pixelBuffer;
    //从CGImage中获取数据
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    //设置从CGImage获取对象的属性
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) *
                         CGImageGetHeight(img));
    
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(
                                             outBuffer.data,
                                             outBuffer.width,
                                             outBuffer.height,
                                             8,
                                             outBuffer.rowBytes,
                                             colorSpace,
                                             kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    
    free(pixelBuffer);
    CFRelease(inBitmapData);
    
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    
    return returnImage;
}

/**
 * 压缩图片到指定文件大小
 *
 * @param image 目标图片
 * @param size 目标大小（最大值）
 *
 * @return 返回的图片文件
 */
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(NSUInteger)size
{
    NSData * data = UIImageJPEGRepresentation(image, 0.1);
    NSUInteger dataKBytes = data.length/1000.0;
    if (dataKBytes <= size)
    {
        return data;
    }
    CGFloat maxQuality = 0.1f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size ) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

/**
 设备是否存在，耳麦，耳机等
 
 @return return value description
 */
+ (BOOL)isHeadsetPluggedIn
{
    AVAudioSessionRouteDescription *route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription *desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones]) {
            return YES;
        }
        else if([[desc portType] isEqualToString:AVAudioSessionPortHeadsetMic]) {
            return YES;
        } else {
            continue;
        }
    }
    return NO;
}

/**
 判断字符串是否包含特殊字符串
 
 @param string 字符串
 @return return value description
 */
+ (BOOL)checkSpecialCharacter:(NSString *)string
{
    NSString *regex = @"[^a-zA-Z0-9\u4E00-\u9FA5,.?:;()!{}<>#*-+=，。、？：；（）！{}+=]➋➌➍➎➏➐➑➒";
    NSRange urgentRange = [string rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: regex]];
    if (urgentRange.location == NSNotFound)
    {
        return NO;
    }
    return YES;
}




+ (NSInteger)getDifferenceOneTime:(NSString *)oneTime nextTime:(NSString *)nextTime {
    // 2.将时间转换为date
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSDate *date1 = [formatter dateFromString:oneTime];
    NSDate *date2 = [formatter dateFromString:nextTime];
    // 3.创建日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    // 4.利用日历对象比较两个时间的差值
    NSDateComponents *cmps = [calendar components:type fromDate:date1 toDate:date2 options:0];
    // 5.输出结果
    NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
    return cmps.day;
}

+ (NSString *)getCurrentTimesDay:(NSInteger)day isNext:(BOOL)isnextMoth {
    
    NSDate *date =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    if (isnextMoth == YES) {
        currentMonth = currentMonth + 1;
    } else {
        currentMonth = currentMonth;
    }
    
    NSString *timestamp = [NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,day];
    return timestamp;
}

+ (BOOL)regularPhone:(NSString *)string {
    
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (string.length != 11) {
        return NO;
    } else {
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(17[5-9])|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:string];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:string];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:string];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}




///////获取日期数据
- (NSArray *)getDateArr {
    //需要的天数
    NSInteger dayNum = 21;
    NSMutableArray *dateArr = [@[] mutableCopy];
    NSDate *date =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay = [[formatter stringFromDate:date] integerValue];
    //获取当前月数的总天数
    NSInteger dayCount = [self getSumOfDaysInMonth:currentYear month:currentMonth];
    
    if (dayCount - currentDay != dayNum) {
        //差数
        NSInteger poor = dayNum - (dayCount - currentDay);
        
        for (NSInteger i = currentDay; i <= dayCount; i++) {
          NSString *timeStr = [self year:currentYear month:currentMonth currenDay:i];
            NSDictionary *dict = @{
                                   @"day" : [self getNum:i],
                                   @"dayStr" : timeStr
                                   };
            
            [dateArr addObject:dict];
        }
        //获取下个月的天数
        NSInteger nextDayCount = [self getSumOfDaysInMonth:currentYear month:currentMonth + 1];
        for (NSInteger i = 0; i <= nextDayCount; i++) {
            if (i < poor - 1) {
                NSString *timeStr = [self year:currentYear month:currentMonth + 1 currenDay:i + 1];
                NSDictionary *dict = @{
                                       @"day" : [self getNum:i + 1],
                                       @"dayStr" : timeStr
                                       };
                [dateArr addObject:dict];
            }
        }
    } else {
        for (NSInteger i = currentDay; i <= dayCount; i++) {
            NSString *timeStr = [self year:currentYear month:currentMonth currenDay:i];
            NSDictionary *dict = @{
                                   @"day" : [self getNum:i],
                                   @"dayStr" : timeStr
                                   };
            
            [dateArr addObject:dict];
        }
    }
    
    if (dateArr.count > 21) {
        [dateArr removeObjectsInRange:NSMakeRange(21, dateArr.count - 21)];
    }
    
    return dateArr.copy;
}

- (NSString *)getNum:(NSInteger)num {
    NSString *str = @(num).description;
    if (str.length == 1) {
        str = [NSString stringWithFormat:@"0%@",str];
    }
    return str;
}

- (NSString *)year:(NSInteger)year month:(NSInteger)month currenDay:(NSInteger)day {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString* beginStr = [NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
    NSDate *beginDate=[formatter dateFromString:beginStr];
    NSString *timeStr = [NSString stringWithFormat:@"%.0f",[beginDate timeIntervalSince1970] * 1000];
    return timeStr;
}

- (NSInteger)getSumOfDaysInMonth:(NSInteger)year month:(NSInteger)month {
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"]; // 年-月
    NSString * dateStr = [NSString stringWithFormat:@"%ld-%ld",(long)year,month];
    NSDate * date = [formatter dateFromString:dateStr];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay
                                   inUnit: NSCalendarUnitMonth
                                  forDate:date];
    return range.length;
}


+ (NSString *)locDatawithKey:(NSString *)name {
    
    NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Bank"ofType:@"json"]];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
    
    NSDictionary *bankDict = [dict objectForKey:@"bankData"];
    
    NSString *bankID = [bankDict objectForKey:name];
    
    return bankID.length == 0 ? @"20" : bankID;
    
}



//获取时间段
+(NSString *)getTheTimeBucket {
    NSDate * currentDate = [NSDate date];
    
    if ([currentDate compare:[Utility getCustomDateWithHour:0]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:9]] == NSOrderedAscending)
    {
        return @"早上好";
    }
    
    else if ([currentDate compare:[Utility getCustomDateWithHour:9]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:11]] == NSOrderedAscending)
    {
        return @"上午好";
    }
    
    else if ([currentDate compare:[Utility getCustomDateWithHour:11]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:13]] == NSOrderedAscending)
    {
        return @"中午好";
    }
    
    else if ([currentDate compare:[Utility getCustomDateWithHour:13]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:18]] == NSOrderedAscending)
        
    {
        return @"下午好";
    }
    
    else
        
    {
        return @"晚上好";
    }
}

//将时间点转化成日历形式

+ (NSDate *)getCustomDateWithHour:(NSInteger)hour

{
    
    //获取当前时间
    
    NSDate * destinationDateNow = [NSDate date];
    
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    
    
    currentComps = [currentCalendar components:unitFlags fromDate:destinationDateNow];
    
    
    
    //设置当前的时间点
    
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    
    [resultComps setYear:[currentComps year]];
    
    [resultComps setMonth:[currentComps month]];
    
    [resultComps setDay:[currentComps day]];
    
    [resultComps setHour:hour];
    
    
    
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    return [resultCalendar dateFromComponents:resultComps];
    
}

@end
